(function(Helper){
	var Storage = Ccay.Storage = {
        create:function(op,type){
        	if(type && type !== "Table")
        	{
        		var target = this[type];
        		if(target)
        			return new target(op);
        	}
        	else
        		return this.createTable(op);
        },
        createTable:function(op){
        	var storage = new this.Table(op);
        	this.Cache.init(storage);
        	return storage;
        },
        createDataTree:function(op){
        	return new this.Tree(op);
        },
        //状态常量
        Status : {
	        inserted:"_inserted",
	        updated:"_updated",
	        deleted:"_deleted",
	        selected:"_selected",
	        halfSelected:"_halfSelected"
	    },
	    //循环返回判断常量
	    ReturnValue : {
	        complete : "complete",
	        next : "continue",
	        last : "last"
	    }
    };
    
    var ModalInterface = {
    	base:{
    		valid:function(data){    		
    			return this.modal.valid(data);
    		},
    		find:function(param,fnHandler){
    			param = this.modal.buildParam(param);
    			var store = this;
    			param.success = function(result){
    				if(result)
    				{
//    					if(result.pageVO)
//    					{
//    						store.pageInf = result.pageVO;
//    						result = result.result;
//    					}
    					store.store(result);
    					fnHandler && fnHandler(result,store);
    				}
    			}
    			this.modal.findSingle(param);
    		}
    	}
    }
    
    Storage.Data = $.IObject({
    	init:function(op){
        	var store = this;
            $.extend(true,store,op);
            //store.initTrigger();
            store.Status = Storage.Status;
            store.ReturnValue = Storage.ReturnValue;
            store.initStore(op);
        },
        //初始化库
        initStore:function(op){
        	 this.dataset || (this.dataset = {});
        },
        //存储数据
        store:function(data,args){
        	if(arguments.length){
	            this.dataset = data || {};
	            if(args)
	            	args.data = data;
	            else
	            	args = {data:data};
	            this.fireTrigger("store",args);
	            return this;
        	}
        	else
        		return this.dataset;
        },
        //清空
        clear:function(args){
            this.dataset = {};
            this.fireTrigger("clear",args);
        },
        len:function(){
        	return !$.isEmptyObject(this.dataset);
        },
        //索引
        at:function(key){
            return this.dataset[key];
        },
        updateItem:function(key,value,args){
    		if(value == null && value == "")
    			delete this.dataset[key];
    		else
    			this.dataset[key] = value;
    		
    		if(args)
    		{
            	args.key = key;
            	args.value = value;
    		}
            else
            	args = {key:key,value:value};
    		this.fireTrigger("update",args);
    	},
        update:function(data,args){
        	var store = this;
        	$.each(data,function(key,value){
        		store.updateItem(key,value,args);
        	})
        }
    },null,true);
    
    Storage.Table = $.IObject({
        init:function(op){
        	var store = this;
            $.extend(true,store,op);
            store.initTrigger();
            store.Status = Storage.Status;
            store.ReturnValue = Storage.ReturnValue;
            store.initStore(op);
        },
        //初始化库
        initStore:function(op){
        	 this.dataset || (this.dataset = []);
        },
        //初始化内置触发器
        initTrigger:function(){
            this.Trigger = {
                store: $.Callbacks(),
                clear: $.Callbacks(),
                update: $.Callbacks(),
                insert: $.Callbacks(),
                remove: $.Callbacks(),
                destroy: $.Callbacks(),
                select: $.Callbacks()
            }
        },
        //执行内置触发器
        fireTrigger:function(name){
        	var trigger = this.Trigger[name],args = Array.prototype.slice.call(arguments,1);
        	trigger && trigger.fireWith(this,args);
        },
        //绑定自定义触发器
        bindTrigger:function(name,fn,type){
        	this._trigger || (this._trigger = {});
        	var trigger = this._trigger[name];
        	trigger || (trigger = this._trigger[name] = $.Callbacks(type));
        	trigger.add(fn);
        },
        //卸载自定义触发器
        unbindTrigger:function(name,fn)
        {
        	var trigger = this._trigger[name];
        	trigger && trigger.remove(fn);
        },
        //清空其定义触发器
        clearTrigger:function(name){
        	var trigger = this._trigger[name];
        	trigger && trigger.empty();
        },
        //执行方法，会根据方法名触发自定义触发器
        run:function(name){
        	var fn = this[name],args;
        	if(fn && $.isFunction(fn)){
        		args = Array.prototype.slice.call(arguments,1);
        		args.unshift(fn);
        		var result = this.proxy.apply(this,args),trigger = this._trigger[name];
        		args[0] = result;
        		trigger && trigger.fireWith(this,args);
        		return result;
        	}
        	return false;
        },
        //存储大小
        len:function(){
        	return this.dataset.length;
        },
        //存储数据
        store:function(data,args){
        	if(arguments.length){
	            this.dataset = data || [];
	            this.fireTrigger("store",data,args);
	            return this;
        	}
        	else
        		return this.dataset;
        },
        //添加数据(触发store)
        append:function(data,index){
            this.dataset = data || [];
             if(!data)
               return this;
             if(!$.isArray(data))
             	data = [data];
               
	         if(index != null){
	         	data.unshift(index,0);
				Array.prototype.splice.apply(this.dataset,data);
	         }
	         else
	         	$.merge(this.dataset,data);
	         	
            this.fireTrigger("store",data,args);
            return this;
        },
        //清空
        clear:function(args){
            this.dataset = [];
            this.fireTrigger("clear",args);
        },
        //循环方法
        each:function(fnHandle){
        	if(fnHandle){
	        	for(var i = 0,len = this.dataset.length;i < len;i++){
	        		if(this.proxy(fnHandle,this.dataset[i],i) === false)
	        			break;
	        	}
        	}
            return this;
        },
        //循环处理方法
        handle:function(fnCheck,fnHandle){
        	//支持对象参数过滤 add by ckf31628  2013-7-17
        	if(fnCheck && typeof fnCheck == "object"){
        		var filterObj = fnCheck;
        		fnCheck = function(item, i , count){
        			for(var attr in filterObj){
        				if(filterObj[attr] !== item[attr]){
        					return false
        				}
        			}
        			return true;
        		}
        	}
        	
        	
            var count = 0,result;
            this.each(function(item,i){
                result = fnCheck ? this.proxy(fnCheck,item,i,count) : true;
                if(result){
                	//判断返回对象是否为结束
                    if(result == this.ReturnValue.complete)
                        return false;
                    count++;
                    this.proxy(fnHandle,item,i,count);
                    //判断返回对象是否为最后一个处理对象
                    if(result == this.ReturnValue.last)
                        return false;
                }
            })
            return count;
        },
        //索引
        at:function(index){
            return this.dataset[index];
        },
        //查询唯一数据项
        findOne:function(fnFilter){
        	var result;
        	this.each(function(item,i,count){
        		if(this.proxy(fnFilter,item,i,count))
        		{
        			result = item;
        			return false;
        		}
        	});
        	return result;
        },
        //过滤方法(参数重载)
        filter:function(fields,fnFilter,copy,fnHandle){
        	//方法重载判断
        	var store = this, op = helper.buildFilterOp(arguments);

            if(!op.fnFilter && !op.copy)
                return store.dataset.slice(0);
                
            var arr = [], record;
            store.handle(op.fnFilter,function(item){
            	record = (op.fields || op.copy) ? Helper.copyField(item,op.fields) : item;
                arr.push(record);
                op.fnHandle && store.proxy(op.fnHandle,record);
            })
            return arr;
        },
        //范围检索方法
        range:function(start,end){
            return this.dataset.slice(start,end);
        },
        //将仓库数据转换到另一个数组中
        map:function(fnMap){
            return $.map(this.dataset,fnMap);
        },
        //排序方法
        sort:function(field, sort,start,end){
            this.dataset = helper.sort(field, sort,this.dataset,start,end);
            return this;
        },
        //分组方法
        group:function(field, fn){

        },
        //状态设置方法
        setStatus:function(item,name,status){
            if(status || status == null)
                item[name] = true;
            else
                delete item[name];
            return this;
        },
        //清除状态方法（根据内置状态对象）
        clearStatus:function(item){
        	if(item = this.getItem(item)){
	        	$.each(this.Status,function(i,s){
	        		delete item[s];
	        	});
        	}
        },
        /********************** 操作 ***************************/
        //item方法，可根据index和item做适应
        getItem:function(index){
        	return $.isNumeric(index) ? this.at(index) : index;
        },
        //设置选择状态方法
        setSelected:function(fnFilter,selected,args){
        	return this.handle(fnFilter,function(item){
        		this.setItemSelected(item,selected,args); 
        	});
        },
        //设置单项选择状态
        setItemSelected:function(item,selected,args){
        	if(item = this.getItem(item))
        	{
        		selected == null && (selected = true);
        		this.innerStatus !== false && this.setStatus(item,this.Status.selected,selected);
        		this.fireTrigger("select",item,selected,args);
        	}
        	return this;
        },
        //插入单项
        insertItem:function(item,start,args){
        	if(item)
        	{
	            this.innerStatus !== false && this.setStatus(item,this.Status.inserted);
	            if(start != null && this.dataset.length)
	                this.dataset.splice(start,0,item);
	            else
	                this.dataset.push(item);
	            this.fireTrigger("insert",item,start,args);
        	}
            return this;
        },
        //插入多项
        insert:function(data,start){
           if(data)
           {
	           if($.isArray(data)){
	               var self = this;
	               $.each(data,function(i,item){
	                    self.insertItem(item,start ? start + i : null)
	               })
	           }
	            else
	                this.insertItem(data,index);
           }
           return this;
        },
        //更新多选
        update:function(data){
//			this.handle(fnFilter,function(item){
//        		this.setItemSelect(item,selected,args);
//        	});
        },
        //更新单项
        updateItem:function(item,change,value,args){
            if(item = this.getItem(item))
            {
            	//重载判断，第二个参数是否为string，是的话构建变化数据
            	if(typeof(change) == "string")
            	{
            		var name = args = change;
            		change = Helper.setObj(name,{},value);
            	}
            	else{
            		args = value;
            	}
            	
                if($.isPlainObject(change))
                    $.extend(true,item,change);
                else{
                    this.dataset[index] = change;
                }
                //新增数据不做编辑状态和触发器触发
                if(!this.isNew(item)){
                	this.innerStatus !== false && this.setStatus(item,this.Status.updated,true);
                	this.fireTrigger("update",item,change,args);
                }
            }
            return this;
        },
        //设置删除状态
        remove:function(fnFilter,delStatus,args){
            return this.handle(fnFilter,function(item){
        		this.setItemSelect(item,delStatus,args);
        	});
        } ,
        //设置单项删除状态
        removeItem:function(item,delStatus,args){
        	var index = $.isNumeric(item) ? item : item._index;
            if(item = this.getItem(item))
            {
                this.innerStatus !== false && this.setStatus(item,this.Status.deleted,delStatus);
                this.fireTrigger("remove",item,delStatus,args);
                return 1;
            }
            return 0;
        },
        //销毁单项
        destroyItem:function(index,args){
        	if(index != null)
        	{
        		 var item = this.dataset.splice(index,1);
        		 if(item.length)
        		 {
	        		 this.fireTrigger("destroy",item[0],args);
	        		 return 1;
        		 }
        	}
        	return 0;
        },
        //根据条件销毁
        destroy:function(fnCondition,args){
            var delCount = 0;
            if(fnCondition)
            {
                var ds = this.dataset,item;
                for(var i = 0,len = ds.length;i < len; i++){
                    var item = ds[i],result = this.proxy(fnCondition,item,i,delCount);
                    if(result)
                    {
                        if(result == this.ReturnValue.complete)
                            break;
                        
                        ds.splice(i,1);
                        i--;
                        delCount++;
                        this.fireTrigger("destroy",item,args);
                        if(result == this.ReturnValue.last)
                            break;
                    }
                }
            }
            return delCount;
        },
        /******************* 状态操作 ********************/
        isNew:function(item){
        	return item[this.Status.inserted];
        },
        isUpdated:function(item){
        	return item[this.Status.updated];
        },
        isDeleted:function(item){
        	return item[this.Status.deleted];
        },
        isSelected:function(item){
        	return item[this.Status.selected];
        },   
        /** @description 获取新增数据
         * 	@param fields {Array/Function} 数据集，或者自定义过滤方法
         *  @param fnFilter {Function} 自定义过滤方法
         *  @param isAll {Boolean} 是否获取全部新增数据（包含预删除的）
         */
        getInsertedRecords:function(fields, fnFilter, isAll){
        	var fn = fnFilter;
        	// 判断是否是bool类型，若是，则给isAll赋值
        	if (typeof(fields) == "boolean") {
        		isAll = fields;
        		fields = null;
        	}
        	// 不获取全部新增数据，则过滤掉预删除的数据
        	if (!isAll) {
        		// 判断是否是function类型，若是，则给fnFilter赋值
        		if(typeof(fields) == "function"){
	            	fnFilter = fields;
	            	fields = null;
	            }
	            // 过滤掉预删除的数据
	        	fn = function(item){
	        		return !this.isDeleted(item) && (!fnFilter || this.proxy(fnFilter,item));
	        	}
        	}
        	return this.filterByStatus(this.Status.inserted,fields,fn);
        },
        getUpdatedRecords:function(fields,fnFilter){
        	if(typeof(fields) == "function"){
            	fnFilter = fields;
            	fields = null;
            }
        	var fn = function(item){
        		return !this.isDeleted(item) && !this.isNew(item) && (!fnFilter || this.proxy(fnFilter,item));
        	}
        	return this.filterByStatus(this.Status.updated,fields,fn);
        },
        /** @description 获取删除数据
         * 	@param fields {Array/Function} 数据集，或者自定义过滤方法
         *  @param fnFilter {Function} 自定义过滤方法
         *  @param isGetInvalid {Boolean} 是否获取无效删除数据（包含新增删除的）
         */
        getDeletedRecords:function(fields, fnFilter, isGetInvalid){
        	var fn = fnFilter;
        	// 判断是否是bool类型，若是，则给isGetInvalid赋值
        	if (typeof(fields) == "boolean") {
        		isGetInvalid = fields;
        		fields = null;
        	}
        	// 不获取无效删除数据，则过滤掉新增删除的数据
        	if (!isGetInvalid) {
        		// 判断是否是function类型，若是，则给fnFilter赋值
        		if(typeof(fields) == "function"){
	            	fnFilter = fields;
	            	fields = null;
	            }
	            // 过滤掉新增删除的数据
	        	fn = function(item){
	        		return !this.isNew(item) && (!fnFilter || this.proxy(fnFilter,item));
	        	}
        	}
        	return this.filterByStatus(this.Status.deleted,fields,fn);
        },
        getSelectedRecords:function(fields,fnFilter){
        	return this.filterByStatus(this.Status.selected,fields,fnFilter);
        },    
        //根据状态（bool判断）过滤
        filterByStatus:function(status,fields,fnFilter,copy,fnHandler){
        	//方法重载判断
            if(typeof(fields) == "function"){
            	fnFilter = fields;
            	fields = null;
            }
            return this.filter(fields,function(item){
                return item[status] && (!fnFilter || this.proxy(fnFilter,item));
            },copy,fnHandler);
        },
        //获取所有变化的值（inserted,updated,deleted）
        getChangedRecords:function(fields,fnFilter,fnHandler,copy){
            var result = {
                insertedRecords : [],
                updatedRecords : [],
                deletedRecords : []
            };
            this.filter(fields,function(item,i){
            	if(!fnFilter || this.proxy(fnFilter,item))
            	{
                 	if(this.isNew(item) && !this.isDeleted(item))
                     	result.insertedRecords.push(item);
                    else if(this.isDeleted(item) && !this.isNew(item))
                     	result.deletedRecords.push(item);
                	else if(this.isUpdated(item))
                     	result.updatedRecords.push(item);
                    
                    fnHandler && this.proxy(fnHandler,item,i);
            	}
            },copy);
            return result;
        },
        /** @description 获取预删除新增数据的值（新增删除的）
         * 	@param fields {Array/Function} 数据集，或者自定义过滤方法
         *  @param fnFilter {Function} 自定义过滤方法
         *  @param isGetInvalid {Boolean} 是否获取无效删除数据（包含新增删除的）
         */
        getPreDeletedRecords:function (fields,fnFilter,fnHandler) {
        	// 判断是否是function类型，若是，则给fnFilter赋值，方法重载判断
            if(typeof(fields) == "function"){
            	fnFilter = fields;
            	fields = null;
            }
            // 过滤获取新增删除的数据
            var fn = function (item) {
	        	return this.isDeleted(item) && (!fnFilter || this.proxy(fnFilter,item));
	        }
        	return this.getInsertedRecords(fields, fn, true);
        }
    });
    
	//仓库缓存
    Storage.Cache = {
    	init:function(storage){
    		
    		//cache模式必须有cacheKey
    		if(storage.cacheKey && storage.cache !== false)
    		{
    			//创建缓存参数
    			var cacheOp = {
    				keys:storage.cacheKey,
    				limitCount:storage.cacheLimit,
    				fnOverLimit : storage.fnOverCacheLimit,
    				caches : this.buildCacheOp(storage.cacheOnlyChanged)
    			};
    			storage.Cache = Ccay.DataCache.createCaches(cacheOp);
    			this.extend(storage).setTrigger(storage.Trigger);
    			this.initInsertCache(storage)
    		}
    	},
    	buildCacheOp:function(onlyChanged){
    		var caches = {updated:{},selected:{
    			buildKey:function(data){
    					if(data[Storage.Status.inserted])
    						return data._cacheKey;
    					return this.fn.buildKey.call(this,data);
    				}
    				},deleted:{}};
    		if(onlyChanged)
    		{
    			updated.buildValue = function(data,key,changed){
					var value = this.getValue(key);
					if(!value)
						value = Helper.copyField(data,this.keys);
					value = $.extend(value,changed);
    				value[Storage.Status.updated] = true;
    				return value;
    			};
    			selected.buildValue = function(data,key,changed){
		    		var value = Helper.copyField(data,this.keys);
    				value[Storage.Status.selected] = true;
    				return value;
    			};
    			deleted.buildValue = function(data,key,changed){
		    		var value = Helper.copyField(data,this.keys);
    				value[Storage.Status.deleted] = true;
    				return value;
    			};
    		}
    		return caches;
    	},
    	extend:function(storage){
    		storage.extend({
    			//重写状态过滤方法
    			filterByStatus:function(status,fields,fnFilter){
    				var cache;
    				switch(status){
    					case this.Status.inserted :
    						cache = this.Cache.insertCache
    						break;
    					case this.Status.updated :
    						cache = this.Cache.getCache("updated");
    						break;
    					case this.Status.deleted :
    						cache = this.Cache.getCache("deleted");
    						break;
    					case this.Status.selected :
    						cache = this.Cache.getCache("selected");
    						break;
    				}
    				if(cache){
    					var store = Storage.create();
    					return store.store(cache.toArray()).filter(fields,fnFilter);
    				}
    				return [];
		        },
		        //重写变化值获取方法
		        getChangedRecords:function(fields,fnFilter){
		        	return {
		                insertedRecords : this.getInsertedRecords(),
		                updatedRecords : this.Cache.getCache("updated").toArray(),
		                deletedRecords : this.Cache.getCache("deleted").toArray()
		            };
		        }
    		});
    		return this;
    	},
    	//在触发器中添加缓存变化
		setTrigger:function(trigger,insertCache){
			trigger.store.add(function(data,pageVO){
    			this.Cache.merge(data);
    			this.Cache.insertCache.merge(data,pageVO);
    		});
    		trigger.clear.add(function(){
    			this.Cache.clear();
    			this.Cache.insertCache.clear();
    		});
    		trigger.update.add(function(item,changed){
    			this.Cache.cache("updated",item,false,changed);
    		});
    		trigger.remove.add(function(item, del) {
    			// 不是新增的数据，就进行删除缓存
    			!this.isNew(item) && this.Cache.cache("deleted", item, !del);
    		});
    		trigger.select.add(function(item,selected){
    			this.Cache.cache("selected",item,!selected);
    		});
		},
		//初始化插入缓存
		initInsertCache:function(storage){
			var insertCache = storage.Cache.insertCache = Ccay.DataCache.create({
					_index:0,
    				keys:storage.cacheKey,
    				//重写缓存值方法
    				buildValue:function(data,key,start){
    					//记录位置参数
			    		data._cachePos = start;
	    				return data;
					},
					buildKey:function(item){
						if(item._cacheKey == null)
							item._cacheKey = this._index++;
						return item._cacheKey;
					},
					//重写合并方法
					merge:function(data,pageVO){
						if(this.length){
						var num = 0,index,
							start = pageVO.startIndex ?  pageVO.startIndex -1 : (pageVO.curPage - 1) * pageVO.pageSize,
							end = pageVO.endIndex ?  pageVO.endIndex -1 : start + pageVO.pageSize;
							//根据分页的信息合并新增项
							this.each(function(item){
								delete item._newIndex;
								delete item._seq;
								index = item._cachePos - start;
								if(index >= 0 && item._cachePos < end){
									data.splice(index + num,0,item);
									num++;
								}
							});
						}
					}
    			});
    			
			storage.Trigger.insert.add(function(item,start){
    			insertCache.cache(item,false,start);
    		});
    		storage.Trigger.destroy.add(function(item){
    			//清楚新增的选择数据
    			storage.setItemSelected(item,false);
    			insertCache.cache(item,true);
    		});
    		storage.Cache.count = function(){
	    		return this.fn.count.call(this) + storage.Cache.insertCache.length;
	    	}
		}
    }
    
	var helper = {
		buildFilterOp:function(args){
			var op = args[0];
			//方法重载判断
        	if(!$.isPlainObject(op))
        	{
	            if(typeof(op) == "function"){
	            	op = {
						fnFilter : args[0],
						copy : args[1],
	            		fnHandle : args[2]
	            	};
	            }
				else {
					op = {
						fields : args[0],
						fnFilter : args[1],
						copy : args[2],
						fnHandle : args[3]
	            	}; 
				}
			}
			return op;
		},
		sort: function(field, sort, dataset, start, end){
			var temp, fieldI, fieldJ, typeI, typeJ,
				asc = sort == "asc";
				
				check = function(item1,item2){
					fieldI = Helper.getObj(field,item1);
					fieldJ = Helper.getObj(field,item2);
					// 判断为空，则给数据赋值空字符串
					if(fieldI == null || ($.type(fieldI) == "number" && isNaN(fieldI))) {
						fieldI = "";
					}
					if(fieldJ == null || ($.type(fieldJ) == "number" && isNaN(fieldJ))) {
						fieldJ = "";
					}
					// 获取类型
					typeI= $.type(fieldI);
					typeJ= $.type(fieldJ);
					// 类型不一样，统一转换成string比较
					if(typeI !== typeJ) {
                        return asc ? fieldI.toString() > fieldJ.toString() : fieldI.toString() < fieldJ.toString();
                    } else {
						//针对时间类型的转化成数字进行比较
                        if(typeI == 'date')
                        {
                            fieldI = fieldI.getTime();
                            fieldJ = fieldJ.getTime();
                        }
                        if(fieldI == fieldJ)
                            return false;//值相等位置不变
						
                        if(typeI == "string")
                        {
                            var r = fieldI.localeCompare(fieldJ);
                            return asc ? r > 0 : r < 0;
                        }
                        else
                            return asc ? fieldI > fieldJ : fieldI < fieldJ;
					}  
				}
   
			var array = dataset;
			//冒泡排序
			array && (array.length > 0) && $.each(array,function(i){
				for(var k=i;k>0;k--){
					var tempBool = check(array[k-1],array[k]);
					if(tempBool){
						var tempValue = array[k];
						array[k] = array[k-1];
						array[k-1] = tempValue;
					}else{
						//不再冒泡时跳出循环
						break;
					}
				}
			});  
			//完善将操作放在后面
			var newArray = new Array(),lockArray=new Array();
			$.each(array,function(i,col){
				if ((col.inner || col.columnType || !col.field) && col.lockEnd) {
					lockArray.push(col);
                }else{
                	newArray.push(col);
                }
			});
			array.splice(0,array.length);
			Array.prototype.push.apply(array,newArray);
			Array.prototype.push.apply(array,lockArray);
			return array; 
		}
		/*	//转换树形的优化算法（未完成，暂屏蔽）
		 * ,buildNodeData:function(node,store,datas){
			var key = store.getKey(node),
				parentKey = store.getParentKey(node);
				
			
		},
		buildParent:function(store,node,parentKey,datas){
			var key;
			for (var i = 0, data; data = datas[i]; i++) {
				key = store.getKey(data);
				if(key == parentKey)
				{
					datas.splice(i,1);
				    --i;
					data._childs = [node];
					parentKey = store.getParentKey(data);
					this.buildChild(store,data,key,datas);
					return parentKey ? arguments.callee(store,data,parentKey,datas) : data;
				}
			}
			return node;
		},
		buildChild:function(store,node,parentKey,datas){
			for (var i = 0, data; data = datas[i]; i++) {
	        	 if (store.getKey(data) == parentKey) {
	            	datas.splice(i,1);
				    --i;
				    node._childs ? node._childs.push(data) : node._childs = [data];
	            }
	        }
	        //查询子的子节点
	        if(node._childs && node._childs.length)
	        {
	        	for (var i = 0, child; child = node._childs[i]; i++) {
	        		arguments.callee(child,datas,field,pField);
	        	}
	        }
		}*/
		//树形节点过滤
		,nodeFilter:function(store,parent,fnFilter,fields,copy,fnHandler){
			var i,node,index = 0,arr = [],arrMatched,isAdd,record;
			for(i in parent.childs){
				node = parent.childs[i];
				if(node.count)
				{
					arrMatched = helper.nodeFilter(store,node,fnFilter,fields,copy,fnHandler);
					isAdd = arrMatched && arrMatched.length;
				}
				else
				{
					arrMatched = null;
					isAdd = store.proxy(fnFilter,node.data,node,index);
				}
				if(isAdd)
				{
					record = (fields || copy) ? Helper.copyField(node.data,fields) : node.data;
					arr.push(record);
					fnHandler && store.proxy(fnHandler,record,node,index);
					if(arrMatched && arrMatched.length)
					{
						store.setStatus(record,"_opened",true);
						arr = arr.concat(arrMatched);
					}
				}
				index++;
			}
			return arr;
		}
	}
	
	Helper.sort = helper.sort;
	//树结构数据仓库
	Storage.Tree = $.IObject({
		initStore:function(op){
			this.clear();
			op && op.dataset && this.store(op.dataset);
		},
        //初始化内置触发器
        initTrigger:function(){
            this.Trigger = {
                insert: $.Callbacks(),
                remove: $.Callbacks(),
                select: $.Callbacks(),
                halfSelect: $.Callbacks()
            }
        },
        clear:function(){
        	this.index = 0;
        	this.dataset = {count:0,_n:true};
        	return this;
        },
		store:function(datas){
			this.clear().buildChild(this.dataset,datas);
			return this;
		},
		//添加节点之外的数据
		append:function(datas){
			var store = this, roots = [],nodes = [],data,i = 0,parentKey,isRoot;
			//过滤出根节点
			for(;data = datas[i];i++)
			{
				isRoot = true;
				parentKey = store.getParentKey(data);
				//判断是否有父节点
				$.each(datas,function(index,item){
					if(index != i && store.checkParent(parentKey,item))
					{
						isRoot = false;
						return false;
					}
				});
				(isRoot ? roots : nodes).push(data);
			}
			//根据根节点附加子节点
			$.each(roots,function(index,root){
				var node = store.insertItem(store.dataset,root);
				nodes.length && store.buildChild(node,nodes,store.getKey(root));
			});
		},
		getKey:function(data)
		{
			return Helper.getObj(this.nodeKey,data)
		},
		getParentKey:function(data){
			return Helper.getObj(this.parentKey,data);
		},
		//判断父数据
		checkRoot: function (data) {
			var pid = this.getParentKey(data);
			if(this.fnCheckRoot && this.fnCheckRoot(pid,data))
				return true;
			return !pid;
		},
		checkParent:function(parentKey,data){
			return this.getKey(data) == parentKey;
		},
		checkChild:function(parentKey,data){
			return this.getParentKey(data) == parentKey;
		},
		//获取数据的子数据
		buildChild:function(parent,datas,parentKey){
			for (var i = 0, data; data = datas[i]; i++) {
				if(parentKey ? this.checkChild(parentKey,data) : this.checkRoot(data))
				{
					datas.splice(i,1);
				    --i;
				    this.insertItem(parent,data);
				}
			}
			if(parent.count)
	    	{
	    		var no,child;
	    		for(no in parent.childs){
	    			child = parent.childs[no];
	    			this.buildChild(child,datas,this.getKey(child.data));
	    		}
	    	}
	    	// 添加剩余无root的数据
	    	!parentKey && datas.length && this.append(datas);
		},
	    each:function(fnHandle,node){
	    	node || (node = this.dataset);
	    	if(node.count)
	    	{
	    		var i,child,index = 0,result;
	    		for(i in node.childs){
	    			child = node.childs[i];
	    			result = this.proxy(fnHandle,child.data,child,index);
	    			if(result === false)
	    				break;
	    			else if(result != Storage.ReturnValue.next)
                        this.each(fnHandle,child);

	    			index++;
	    		}
	    	}
	    },
	    //循环处理方法
        handle:function(fnCheck,fnHandle,node){
            var result,count = 0;
            this.each(function(item,node,i){
                result = fnCheck ? this.proxy(fnCheck,item,node,i,count) : true;
                if(result){
                	//判断返回对象是否逃过
                	
                    //判断返回对象是否为结束    
                    if(result == Storage.ReturnValue.complete)
                        return false;
                    count++;
                    this.proxy(fnHandle,item,node,i,count);
                    //判断返回对象是否为最后一个处理对象
                    if(result == Storage.ReturnValue.last)
                        return false;
                   else	if(result == Storage.ReturnValue.next)
                        return Storage.ReturnValue.next;
                }
            },node)
            return count;
        },
        filter:function(fields,fnFilter,copy,fnHandle,node){
        	var arr = [],op = helper.buildFilterOp(arguments);
			op.node = arguments.length == 5 ? node : fnHandle;

			this.handle(op.fnFilter,function(item,node,i){
				record = (op.fields || op.copy) ? Helper.copyField(item,op.fields) : item;
				arr.push(record);
				op.fnHandle && this.proxy(op.fnHandle,record,node,i);
			},op.node);
			return arr;
        },
	    filterByDeep:function(maxDeep,fnHandle,node){
	    	return this.filter(function(item,node,i){
				return item._deep <= maxDeep
			},null,fnHandle,node);
	    },
	    //tree的节点过滤方法，保存tree结构的筛选方式
	    nodeFilter:function(fields,fnFilter,copy,fnHandler,node){
	    	var op = helper.buildFilterOp(arguments);
	    	op.node = arguments.length == 5 ? node : fnHandler;
        	node || (node = this.dataset);
        	if(node.count)
				return helper.nodeFilter(this,node,op.fnFilter,op.fields,op.copy,op.fnHandler);
			return [];
	    },
	    getChilds:function(node,fnFilter){
	    	return this.filter(fnFilter,null,null,node);
	    },
	    at:function(no){
	    	if(no._n)
	    		return no;
	    	else
	    		no = this.getTreeNo(no);

	    	no = no.replace(/\./g,".childs.");
	    	return Helper.getObj(no,this.dataset.childs);
	    },
	    getTreeNo:function(node){
	    	if(typeof(node) != 'string')
	    	{
	    		if(node._n)
	    			return node.data._treeNo;
	    		else
	    			node = node._treeNo || "";
	    	}
	    	return node;
	    },
	    getParent:function(node){
	    	return this.getNodeInf(node).parent;
	    },
	    getNodeInf:function(node){
	    	var no = this.getTreeNo(node),parent,key;
	    	if(no){
	    		no = no.split('.');
	    		if(key = no.pop())
	    			parent = this.at(no.join("."));
	    	}
	    	else
	    		parent = this.dataset;
	    		
	    	return {key : key,parent:parent};
	    },
	    insertItem:function(node,child,args){
	    	node = node ? this.at(node) : this.dataset;
	    		
			var nodeData = node.data;
			//判断是否为根节点
			if(nodeData){
				child._treeNo = (nodeData._treeNo ? nodeData._treeNo + "." : "")  + this.index;
				child._deep = nodeData._deep != null ? nodeData._deep + 1 : 0;
			}
			else
			{
				child._treeNo = this.index + "";
				child._deep = 0;
			}
			node.count++;
			node.childs || (node.childs = {});
			var childNode = node.childs[this.index++] = {data:child,count:0,_n:true};
			this.fireTrigger("insert",childNode,node,args);
			return childNode;
		},
	    insert:function(node,datas){
	    	for(var i = 0,data;data = datas[i];i++){
	    		this.insertItem(node,data);
	    	}
	    },
	    toggleNode:function(node,open){
	    	if(node = this.at(node))
	    	{
	    		if(node.count){
		    		this.setStatus(node.data,"_opened",open);
		    		if(open){
		    			var newChilds = [],
		    				childs = this.getChilds(node,function(item){
		    				if(this.isNew(item))
		    				{
		    					newChilds.push(item);
		    					return false;
		    				}
		    				else if(!this.isOpened(item))
		    					return Storage.ReturnValue.next;
		    				else 
		    				return true;
		    			});
		    			return newChilds.concat(childs);
		    		}
	    		}
	    	}
	    	return [];
	    },
	    isOpened:function(data){
	    	return data._opened;
	    },
	    setNodeStatus:function(node,name,status){
	    	if(node = this.at(node)){
		    	this.setStatus(node.data,name,status);
		    	this.each(function(item){
		    		this.setStatus(item,name,status);
		    	},node);
	    	}
	    	return this;
	    },
	    //设置节点选择状态
        setSelected:function(node,selected,args){
        	return this.setNodeStatus(node,Storage.Status.selected,selected);
        },
        //设置单项选择状态
        setItemSelected:function(item,selected,args){
        	this.setStatus(item,Storage.Status.selected,selected);
        },
         //设置父节点的半选择状态
        setHalfSelected:function(item,selected,args){
        	if(item = this.getItem(item))
        	{
        		selected == null && (selected = true);
        		this.innerStatus !== false && this.setStatus(item,Storage.Status.halfSelected,selected);
        		this.fireTrigger("halfSelect",item,selected,args);
        	}
        	return this;
        },
        remove:function(node,delStatus,args){
            if(node = this.at(node)){
            	var name = Storage.Status.deleted;
		    	this.setStatus(node.data,name,delStatus);
		    	this.each(function(item){
		    		if(this.isNew(item))
		    			this.destroy(item);
		    		else
		    			this.setStatus(item,name,delStatus);
		    	},node);
	    	}
	    	return this;
        },
//        removeItem:function(node,delStatus,args){
//            return this.setNodeStatus(node,Storage.Status.deleted,delStatus);
//        },
        destroy:function(node){
        	var inf = this.getNodeInf(node),parent = inf.parent;
        	if(inf.key && parent)
        	{
        		var target = parent.childs[inf.key];
	    		if(target){
	    			delete parent.childs[inf.key];
	    			parent.count--;
	    			return true;
	    		}
        	}
	    	return false;
        }
	},Storage.Table);
})(Ccay.DataHelper);